<?php

class ProductsController extends AppController {

	var $helpers = array('Html','Text','Javascript','Ajax','Image','Lightbox','Rss');
	
	function add() {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_PROD)) {// must be producer
				//get producer ID
				if ($this->checkLevel(AUTH_ADMIN)) {
					$id = $this->Session->read('Managing.producer');
					$prod = $this->Product->Producer->find("Producer.producer_id = '" . $id . "'");
				} else {
					$prod = $this->Product->Producer->find("Member.username = '" . $this->userInfo['username'] . "'");
				}
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		//print_r($prod);
		if (!empty($this->data)) {
			if (empty($this->data['Product']['inventory'])) {
				$this->data['Product']['inventory'] = 0;
			}
			if (!$this->Product->save($this->data)) {
				
			} else {
				$this->Session->setFlash("Product Saved!", 'message_ok');
				$destination = ($this->data['Go']['add_another']) ? '/products/add' : '/products/manage';
				unset($this->data);
				$this->redirect($destination);
			}
		} else {
			$this->data = $prod;
		}
		$this->set('cats', $this->Product->Subcategory->optionsArray());
		$this->render();
	}
	
	function edit($id) {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_PROD)) {// must be producer
				//load product & check producer ID
				$prod = $this->Product->find("Product.product_id = " . $id);
				if (!$this->checkLevel(AUTH_ADMIN)) {
					if ($prod['Product']['producer_id'] != $this->userInfo['producer_id']) {
						$this->notAuth();
					}
				}
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		if (!empty($this->data)) {
			if (!$this->Product->save($this->data)) {
				
			} else {
				$this->Session->setFlash("Product Saved!", 'message_ok');
				$this->redirect('/products/manage');
			}
		} else {
			$this->data = $prod;
		}
		$this->set('cats', $this->Product->Subcategory->optionsArray());
		$this->render();
	}
	
	function makeOrderable($id, $show, $page) {
		if (!$this->checkLevel(AUTH_ADMIN)) {
			$this->notAuth();
		}
		$product = $this->Product->find("Product.product_id = " . $id);
		
		$delivery_id = $this->deliveryId;
		
		$o = new Orderable();
		$o->addForProduct($product);
		$this->Session->setFlash("Orderable!", 'message_ok');
		$this->redirect('/products/manage/' . $show . '/' . $page);
	}
	
	function delete($id){
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_PROD)) {// must be producer
				//load product & check producer ID
				$prod = $this->Product->find("Product.product_id = " . $id);
				if ($this->checkLevel(AUTH_ADMIN)) {
					// let it go through.
				} else if ($prod['Product']['producer_id'] != $this->userInfo['producer_id']) {
					$this->notAuth();
				}
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		
		$this->Product->archive($id);
		$this->Session->setFlash("Product Deleted.",'message_ok');
		$this->redirect('/products/manage');
	}
	
	function show($page = 1,$special = null,$id = null) {
		$this->checkSession();
		$args = '';
		if ($special != null) {
			$args = '/' . $special;
		}
		if ($id != null) {
			$args .= '/' . $id;
		}
		$cond = null;
		$limit = 25;
		$order = 'Product.producer_id';
		if ($special == AUTH_PROD) {
			$cond = "Product.producer_id = '" . $id . "' and Product.archived = 0";
		}
		$prods = $this->Product->findAll($cond,null,$order,$limit,$page,2);
		$max = $this->Product->findCount($cond);
		if ($max == 0) {
			$this->Session->setFlash('There are no items there to show.');
			$this->redirect('/members/menu');
		}
		$this->set('products', $prods);
		$this->set('page', array('Page'=>$page,'Limit'=>$limit,'Max'=>$max));
		$this->set('args',$args);
	}
	
	function manage($show = '', $page = 0, $id = '') {
		if ($this->checkSession()) {
			if(!($this->checkLevel(AUTH_PROD))) { 
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		if ($this->checkLevel(AUTH_ADMIN)) {
			if ($id != '') {
				$this->Session->write('Managing.producer', $id);
			} else {
				$id = $this->Session->read('Managing.producer');
			}
		} else {
			$id = $this->userInfo['producer_id'];
		}
		
		if ($show == '') {
			if ($this->Session->check('Managing.show')) {
				$show = $this->Session->read('Managing.show');
			} else {
				$show = 'all';
			}
		}
		if ($page == 0) {
			if ($this->Session->check('Managing.page')) {
				$page = $this->Session->read('Managing.page');
			} else {
				$page = 1;
			}
		}
		
		$this->Session->write('Managing.show', $show);
		$this->Session->write('Managing.page', $page);
		
		$args = '/' . $show;
		$cond = null;
		$limit = 25;
		$order = null;
		$cond = "Product.producer_id = '" . $id . "' and Product.archived = 0";
		if ($show == 'listed') {
			$cond .= " and Product.donotlist = 0";
		} else if ($show == 'unlisted') {
			$cond .= " and Product.donotlist = 1";
		}
		$prods = $this->Product->c_find_any($cond,$order,$limit,$page);
		$max = $this->Product->findCount($cond);
		if ($max == 0) {
			$this->Session->setFlash('There are no items there to show.');
			$this->redirect('/members/menu');
		}
		$this->set('show', $show);
		$this->set('products', $prods);
		$this->set('page', array('Page'=>$page,'Limit'=>$limit,'Max'=>$max));
		$this->set('args',$args);
	}
	
	function basicSearch() {
		App::import('Sanitize');
		$namedParams = array();
		$go = isset($this->params['form']['search']) && !empty($this->params['form']['search']);
		
		if ($go) {
			$q = split(' ', $this->params['form']['search']);
			$searchText = array();
			$currentField = 'name';
			foreach ($q as $term) {
				if (strpos($term, ':') !== false) {
					list($field, $what) = split(':', $term);
					$currentField = $field;
					if (!empty($what)) {
						$namedParams[$currentField] = $what;
					}
				} else {
					if (!empty($term)) {
						if (!isset($namedParams[$currentField])) {
							$namedParams[$currentField] = $term;
						} else {
							$namedParams[$currentField] .= ' ' . $term;
						}
					}
				}
			}
			if (!empty($namedParams['name'])) {
				$search = $namedParams['name'];
			} else {
				$search = '';
			}
			$this->params['named'] = $namedParams;
			$this->search();
		} else {
			$search = '';
			$this->set('products', array());
		}
		
		$this->set('search',$search);
		//$this->set('products',$products);
	}
	
	function search() {
		App::import('Sanitize');
		
		$query = array('conditions' => array(), 'limit'=>null, 'page'=>null, 'order'=>'Product.product_name');
		
		$args = $this->params['named'];
		
		unset($args['view']);
		
		if (isset($args['order'])) {
			$query['order'] = Sanitize::escape($args['order']);
			unset($args['order']);
		}
		
		if (isset($args['limit'])) {
			$l = $args['limit'];
			if (is_numeric($l)) {
				$query['limit'] = Sanitize::escape($l);
				$query['page'] = 1;
			}
			unset($args['limit']);
		}
		
		if (isset($args['page'])) {
			$p = $args['page'];
			if (is_numeric($p)) {
				$query['page'] = Sanitize::escape($p);
				if (!isset($query['limit'])) {
					$query['limit'] = 25;
				}
			}
			unset($args['page']);
		}
		
		if (isset($args['name'])) {
			$query['conditions'][] = 'Product.product_name LIKE \'%' . Sanitize::escape($args['name']) . '%\'';
			unset($args['name']);
		}
		
		if (isset($args['from'])) {
			$query['conditions'][] = 'Member.business_name LIKE \'%' . Sanitize::escape($args['from']) . '%\'';
			unset($args['from']);
		}
		
		if (isset($args['desc'])) {
			$query['conditions'][] = 'Product.detailed_notes LIKE \'%' . Sanitize::escape($args['desc']) . '%\'';
			unset($args['desc']);
		}
		
		foreach($args as $operator => $what) {
			$what = Sanitize::escape($what);
			if (strpos($operator, '.') === false) {
				$operator = 'Product.' . $operator;
			}
			$query['conditions'][] = $operator . ' = \'' . $what . '\'';
		}
		
		if (empty($query['conditions'])) {
			$query['conditions'][] = 0;
		} 
		
		$products = $this->Product->c_find($query['conditions'], $query['order'], $query['limit'], $query['page']);
		
		$this->set('query', $query);
		$this->set('products', $products);
	}
	
	function view($what = 'all') {
		$p = new Product();
		$products = array();
		if ($what == "all") {
			$products = $p->c_find();
		} else if (($what == 'changed') || ($what = 'new')) {
			$cur_del = Configure::read('Delivery');
			$prev_del = array();
			$start_id = $cur_del['delivery_id'];
			$d = new Delivery();
			while (empty($prev_del) && ($start_id != 0)) {
				$start_id = $start_id - 1;
				$prev_del = $d->find("Delivery.delivery_id = " . $start_id);
			}
			$start_date = $prev_del['Delivery']['order_open'];
			list ($start_date, $start_time) = split(' ', $start_date);
			$end_date = $cur_del['order_closed'];
			list ($end_date, $end_time) = split(' ', $end_date);
			$field = ($what == 'changed') ? 'Product.modified' : 'Product.created';
			$sorting = ($this->RequestHandler->isRss()) ? $field . ' DESC' : 'Category.category_name, Subcategory.subcategory_name';
			$products = $p->c_find($field . ' < "' . $end_date . '" AND ' . $field . ' > "' . $start_date . '"', $sorting);
		}
		$this->set('sorting', 'Category');
		$this->set('requested', $what);
		$this->set('dates', $start_date . ' and ' . $end_date);
		$this->set('products', $products);
	}
	
	function info($id = null) {
		if (empty($id)) {
			$this->Session->setFlash("You must select a product to get info on!", 'error');
			$this->redirect('/categories');
		}
		$products = $this->Product->c_find("Product.product_id = $id");
		$product = $products[0];
		App::import('Model', 'Producer');
		$p = new Producer();
		$m = $p->getMemberInfo($product['Product']['producer_id']);
		//$product['Producer']['business_name'] = $m['Member']['business_name'];
		$this->set('product', $product);
		App::import('Model', 'Picture');
		$pics = new Picture();
		$u = $pics->getUserIdFromEmail($m['Member']['email_address']);
		$this->set('flickr_user', $u);
		$pic_error = $pics->getError();
		$pictures = array();
		if ($pic_error === false) {
			$pictures = $pics->findAll(array('user_id' => $u['nsid'], 'tags' => "" . $product['Product']['product_id']));
			$pic_error = $pics->getError();
		}
		$photos = array();
		if (!empty($pictures['photo'])) {
			foreach($pictures['photo'] as $photo) {
				$photos[] = array('thumb' => $pics->getUrl($photo, 'thumbnail'), 'medium' => $pics->getUrl($photo), 'title' => $photo['title']);
			}
		}
		$this->set('pictures', $pictures);
		$this->set('photos', $photos);
		$this->set('pic_error', $pic_error);
		
	}

}
